package com.quan.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExcludeUtils {
	
	private static Logger logger = LoggerFactory.getLogger(ExcludeUtils.class);

	/**
	 * 不参与拦截的域名
	 * 
	 * @param request
	 * @return
	 */
	public static boolean excludeDomain(HttpServletRequest request, String key) {
		String excludesDomain = EncryptPropertyConfigurer.getValue(key) ;
		
		// 没有设定excludes时，所有经过拦截器的请求都需要被处理
		if (StringUtils.isEmpty(excludesDomain)) {
			return false;
		}

		// 获取当前请求域名
		String serverName = request.getServerName();

		Pattern p = Pattern.compile(excludesDomain);
		Matcher m = p.matcher(serverName);
		// 正则表达式匹配URI被排除，不需要拦截
		boolean isExcluded = m.find();
		if (isExcluded) {
			logger.debug("无需拦截的域名==>{}", serverName);
		}

		return isExcluded;
	}
	
	public static boolean excludeDomain(HttpServletRequest request) {
		return excludeDomain(request, "excludes.domain") ;
	}

	/**
	 * 不参与拦截的请求
	 * @param request
	 * @param key 属性文件中的KEY
	 * @return
	 */
	public static boolean excludeRequest(HttpServletRequest request, String key) {
		String excludesRequest = EncryptPropertyConfigurer.getValue(key) ;
		// 没有设定excludes是，所有经过filter的请求都需要被处理
		if (StringUtils.isEmpty(excludesRequest)) {
			return false;
		}

		// 获取去除context path后的请求路径
		String contextPath = request.getContextPath();
		String uri = request.getRequestURI();
		uri = uri.substring(contextPath.length());

		Pattern p = Pattern.compile(excludesRequest);
		Matcher m = p.matcher(uri);
		// 正则表达式匹配URI被排除，不需要拦截
		boolean isExcluded = m.find();
		if (isExcluded) {
			logger.debug("无需拦截的请求==>{}", request.getRequestURL());
		}

		return isExcluded;
	}
	
	public static boolean excludeRequest(HttpServletRequest request) {
		return excludeRequest(request, "excludes.request") ;
	}
	
}
